package com.chengjue.controller;


import com.chengjue.service.UserService;
import com.chengjue.common.Const;
import com.chengjue.common.ServerResponse;
import com.chengjue.model.UserModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Api(value = "user")
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "register", method = RequestMethod.POST)
    @ApiOperation(value = "用戶注冊", httpMethod = "GET", response = ServerResponse.class, notes = "注冊信息")
    public ServerResponse<String> createUser(UserModel user) {
        return userService.register(user);
    }


    /**
     * 登录
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ApiOperation(value = "用戶登录", httpMethod = "POST", response = ServerResponse.class, notes = "手機號 密碼")
    public ServerResponse<UserModel> login(UserModel user, HttpSession session) {
        ServerResponse<UserModel> response = userService.login(user);
        if (response.isSuccess()) {
            session.setAttribute(Const.CURRENT_USER, response.getData());
        }
        return userService.login(user);
    }


    @RequestMapping(value = "reset", method = RequestMethod.PUT)
    @ApiOperation(value = "重置密码", httpMethod = "PUT", response = ServerResponse.class, notes = "旧密码 新密码")
    public ServerResponse<String> resetPassWord(String old, String newPassword, HttpSession session) {
        logger.error("resetPassWord password:"+old);
        //可以判断下id是否为当前用户
        //防止越权
        UserModel userModel = (UserModel) session.getAttribute(Const.CURRENT_USER);
        if(userModel == null){
            return ServerResponse.createByErrorMessage("用户未登录");
        }
        return userService.resetPassWord(userModel.getId(), old, newPassword);
    }


}
